// const AUTH = require('../../utils/auth.js')
import Toast from '../../components/dist/toast/toast';
import dateUtil from '../../utils/dateUtil.js';
import { CustomerModel } from '../../models/CustomerModel.js'
let Customer = new CustomerModel()
const today = dateUtil.getDate('yyyy-MM-dd',0)
let App = getApp()
Page({
  data: {
    minDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    formatter(day) {
      return day;
    },
    signIn:'',//判断今天是否签到
    score:0,
    openId:'',
    customerId:'',
    wxlogin:false,
    

  },
  onLoad: function(options) {
    
  },
  onShow: function() {
    this._init()
  },
  _init:function(){
    this._getCustomer()
  },
   
  _getOpenId:function(){
    let openId = App.globalData.openId
    this.setData({openId})
    return openId
  },
  _getCustomer:async function(){
    let customer = {
      openid:this._getOpenId()
    }
    let result = await Customer.getCustomer(customer)
    this.setData({
      signIn:result[0].sign_in,
      score:result[0].score,
      customerId:result[0]._id
    })
    console.log('customer',result)
    //  如果今天已签到
    console.log('signin',result[0].sign_in, today)
    if(result[0].sign_in == today){
      this._setSomeDay(new Date().getDate())
    }
  },
  // 设置某天 someday 为已签到
  _setSomeDay:function(someday){
    this.setData({
      formatter(day){
        const date = day.date.getDate();
        if(someday == date){
            day.bottomInfo = '已签到'
        }
        return day
      }
    })
  },
 
  // 签到
  _signIn:async function(){
    let result = await wx.getSetting()
    // 校验用户是否授权登录
    if(!result.authSetting['scope.userInfo']){
        Toast.fail('请先登录后，再签到!')
    }else{
      // 判断今日是否已经签到
      //  如果今天已签到
    
    if(this.data.signIn == today){
      Toast.success('今日已签到!')
    }else{
      // 设置今天为已签到
      this._setSomeDay(new Date().getDate())
      this.setData({
        signIn:true
      })
      Toast.success('签到成功!')
      this._updateCustomer()
    }
    }
    
    
  },
  _updateCustomer: async function(){
    let customer = {
      score : parseInt(this.data.score) + 2,
      sign_in: today
    }
    await Customer.updateCustomer(customer, this.data.customerId)
  }
  
})